package main

import (
	"fmt"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/toolbox"
	_ "github.com/go-sql-driver/mysql"
	"os"
	"os/signal"
	"smart_home/task/router"
	"syscall"
	"time"
)

func init() {
	// 日志
	logs.SetLogger(logs.AdapterFile, `{"filename":"logs/logs.log", "color":true}`)
	logs.EnableFuncCallDepth(true)
	logs.SetLogFuncCallDepth(3)
	logs.Async()

	time.Sleep(1 * time.Second)
}

func main() {
	logs.Debug("task server starting....")
	fmt.Println("task server starting....")

	// 启动定时器
	startTask()

	// 开启任务
	go toolbox.StartTask()
	defer toolbox.StopTask()

	done := make(chan os.Signal, 1)
	//signal.Notify(done)
	signal.Notify(done, os.Kill, os.Interrupt, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)

	fmt.Println("信号:" , <-done)

	fmt.Println("开始退出...")
	logs.Debug("开始退出...")
	fmt.Println("执行清理...")
	logs.Debug("执行清理...")
	fmt.Println("结束退出...")
	logs.Debug("结束退出...")
	os.Exit(0)
}

func startTask()  {
	ls := router.GetRouters()
	for _, v := range ls {
		t := toolbox.NewTask(v.Tname, v.Spec, v.Fn)
		if err := t.Run(); err != nil {
			logs.Error(err)
		}
		toolbox.AddTask(v.Tname, t)
	}
}